package com.cjl.jvm.gc;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

public class SoftRef {
    public static void collect() throws Exception{
        System.out.println("SoftRef.collect start");
        System.gc();
        System.out.println("SoftRef.collect end");
        Thread.sleep(2000);
    }
    public static void main(String[] args) throws Exception {
        System.out.println("创建软引用");
        Referred stong = new Referred();
        SoftReference<Referred> soft = new SoftReference<>(stong);
        SoftRef.collect();

        System.out.println("SoftRef.main 删除软引用");
        stong = null;
        SoftRef.collect();

        if (soft.get() == null){
            System.out.println("SoftRef.main soft.get = null");
        }

        System.out.println("SoftRef.main 开始堆占用");

        try {
            List<SoftRef> heap = new ArrayList<>(100);
            int i = 0;
            while (true){
                heap.add(new SoftRef());
            }
        }catch (OutOfMemoryError error){
            System.out.println("SoftRef.main 内存溢出");
            if (soft.get() == null){
                System.out.println("SoftRef.main soft.get = null");
            }
        }


        System.out.println("SoftRef.main END");

    }
}
